/**
 * calculator
 *
 * @author : tzy
 * @Date : 2021-03-16
 * @Description:
 **/

package com.tang.calculator.symbols;

import com.tang.calculator.context.CalculateContext;
import com.tang.calculator.utils.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Stack;

@Component
public class DivideSymbol implements OperatorSymbol, Calculation {
    @Autowired
    CheckUtils checkUtils;
    @Autowired
    ValueSymbolFactory valueSymbolFactory;

    public int getPriority() {
        return 50;
    }

    @Override
    public void simpleOperate(CalculateContext context) {
        Stack<ValueSymbol> valueStack = context.getValueStack();
        ValueSymbol value1 = valueStack.pop();
        ValueSymbol value2 = valueStack.pop();

        BigDecimal res = value2.getValue().divide(value1.getValue(), value2.getValue().scale(), BigDecimal.ROUND_HALF_UP);
        ValueSymbol valueSymbol = valueSymbolFactory.create(res.toString());

        valueStack.push(valueSymbol);
    }

    public String getName() {
        return "/";
    }

    /**
     * 校验
     *
     * @param context
     * @return
     */
    @Override
    public String check(CalculateContext context, String replace) {
        if (replace.contains(getName())) { //(1+sum(0,3)+1+2)*3
            int a = 0, i = 0;
            while (true) {
                i++;
                String[] strs = new String[2];
                replace = replace.substring(a);
                int anInt = checkUtils.getInt(replace, getName(), context.getCount());
                if (anInt == -1) return null;
                if (anInt == 0) return "第" + i + "个" + getName() + "号运算符使用错误";
                if (replace.length() - 1 <= anInt) return "第" + i + "个" + getName() + "号运算符使用错误";
                strs[0] = checkUtils.Upstream(replace, anInt);
                String downstream = checkUtils.Downstream(replace, anInt);
                if ("0".equals(downstream)) return "第" + i + "个" + getName() + "号运算符使用错误,0不能作为被除数";
                strs[1] = downstream;
                if (checkUtils.operator(strs)) return "第" + i + "个" + getName() + "号运算符使用错误";
                a = anInt + 1;
            }
        }
        return null;
    }
}
